package cn.tedu.file;

import java.io.*;
import java.util.Scanner;

/*本类用于实现IO综合练习之文件复制案例*/
public class TestCopeFile {
    public static void main(String[] args) {
        System.out.println("请输入源文件路径");
        String f=new Scanner(System.in).nextLine();
        System.out.println("请输入新文件路径");
        String t=new Scanner(System.in).nextLine();


        //ZFCope(f,t);
        ZJCope(f,t);
    }

    private static void ZJCope(String f, String t) {
        BufferedInputStream in=null;
        BufferedOutputStream out=null;
        try {
            in=new BufferedInputStream(new FileInputStream(new File(f)));
            out=new BufferedOutputStream(new FileOutputStream(t));
            int b;
            while ((b=in.read())!=-1){
                out.write(b);
            }
            System.out.println("恭喜您,文件复制成功");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("文件复制失败");
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void ZFCope(String f, String t) {
        Reader in=null;
        Writer out=null;

        try {
            in = new BufferedReader(new FileReader(new File(f)));
            out= new BufferedWriter(new FileWriter(t));

            int b;
            while ((b=in.read())!=-1){
                out.write(b);
            }
            System.out.println("恭喜您,文件复制成功");
        }catch (Exception e){
            System.out.println("很抱歉,文字复制失败");
            e.printStackTrace();
        }finally {
            /*1.关流是有顺序的,如果有多个流,最后创建的要最先关闭
            2.多条关流语句需要各自try-catch
            */
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
